package com.chukun.netty.protobuf;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Random;

/**
 * @author chukun
 * protobuf客户端程序
 */
public class NettyProtobufClientHandler extends SimpleChannelInboundHandler<MessageData.MessageInfo> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageData.MessageInfo messageInfo) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Random random = new Random();
        int type = random.nextInt(3);
        MessageData.MessageInfo message = null;
        if(type==1){
            //发送普通person的数据类型
            message = MessageData.MessageInfo.newBuilder()
                    .setDataType(MessageData.MessageInfo.DataType.PersonType)
                    .setPerson(MessageData.Person.newBuilder()
                            .setId("001")
                            .setName("张三")
                            .setAge(18)
                            .build()).build();
        }else if(type==2){
            //发送teacher的数据类型
            message = MessageData.MessageInfo.newBuilder()
                    .setDataType(MessageData.MessageInfo.DataType.TeacherType)
                    .setTeacher(MessageData.Teacher.newBuilder()
                            .setId("002")
                            .setName("码云")
                            .setAge(23)
                            .setCourse("中文")
                            .setAddress(MessageData.Address.newBuilder()
                                    .setProvinceCode("bj001")
                                    .setCityCode("cp001")
                                    .setAreaCode("hlg002")
                                    .build())
                            .build()).build();
        }else {
            //发送Driver的数据类型
            message = MessageData.MessageInfo.newBuilder()
                    .setDataType(MessageData.MessageInfo.DataType.DriverType)
                    .setDriver(MessageData.Driver.newBuilder()
                            .setId("003")
                            .setName("刘志")
                            .setAge(28)
                            .setDriverBus("bj460")
                            .setAddress(MessageData.Address.newBuilder()
                                    .setProvinceCode("bj002")
                                    .setCityCode("hd001")
                                    .setAreaCode("xzm002")
                                    .build())
                            .build()).build();
        }
        ctx.writeAndFlush(message);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
